package org.mics.lang.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程管理器
 * @author mics
 * @date 2022-8-19
 * @version  1.0
 */
public class TaskThreadManager {
	
	/**
	 * 初始化线程池
	 */
	ThreadPoolExecutor executor = new ThreadPoolExecutor(50,
		  250,
		  10L,
		  TimeUnit.SECONDS,
		  new LinkedBlockingQueue<Runnable>(1024),
		  new ThreadPoolExecutor.AbortPolicy()
		  );
	
	private TaskThreadManager() {
    	
    }
	
	/**
	 * 线程池管理器
	 */
    public static final TaskThreadManager TASK_THREAD_MANAGER = new TaskThreadManager();


    /**
     * 对外
     * @return
     */
    public static TaskThreadManager get() {
        return TASK_THREAD_MANAGER;
    }
    
    /**
     * 对外
     * @return
     */
    public static TaskThreadManager getSingle() {
    	TaskThreadManager singleThreadManager = new TaskThreadManager();
        return singleThreadManager;
    }
    
    /**
     * 执行线程
     * @param task
     */
    public void execute(Runnable task) {
        executor.execute(task);
    }
    
    /**
     * 执行线程
     * @param task
     * @return 
     */
    public  Future<?> execute(Callable<?> task) {
    	Future<?> future =   executor.submit(task);
    	return future;
    }

	public void shutdown() {
		executor.shutdown();
	}

	public boolean awaitTermination(int i, TimeUnit time) {
		try {
			return executor.awaitTermination(i, time);
		} catch (InterruptedException e) {
			return true;
		}
	}

	public long getCompletedTaskCount() {
		return executor.getCompletedTaskCount();
	}
    
	
	/**
	 * 结束线程池
	 * @author mics
	 * @date 2022-8-19
	 * @version  1.0
	 * @return
	 */
	public boolean compleate() {
		executor.shutdown();
		while(!executor.isTerminated()) {
			try {
				Thread.sleep(50);
			}catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return true;
	}
    
	 
}
